package com.hongshan.wallet.core.main

import android.annotation.SuppressLint
import android.app.Activity
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.content.Intent
import android.databinding.ObservableField
import android.databinding.ViewDataBinding
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.NotificationBuilder
import com.allenliu.versionchecklib.v2.builder.UIData
import com.aurelhubert.ahbottomnavigation.AHBottomNavigation
import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem
import com.hongshan.wallet.BR
import com.hongshan.wallet.BuildConfig
import com.hongshan.wallet.Constant
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.R
import com.hongshan.wallet.base.BaseFragmentPagerAdapter
import com.hongshan.wallet.base.BaseOnPropertyChangedCallback
import com.hongshan.wallet.base.MyActivity
import com.hongshan.wallet.bean.UserDescBean
import com.hongshan.wallet.core.home.HomeFragment
import com.hongshan.wallet.core.trading.TradingFragment
import com.hongshan.wallet.core.wallet.WalletFragment
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.router.RouterIndex
import com.hongshan.wallet.router.go
import com.hongshan.wallet.toast
import com.hongshan.wallet.tryRun
import com.hongshan.wallet.util.MyActivityManager
import com.jaeger.library.StatusBarUtil
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.appbar.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


@Route(path = RouterIndex.MAIN)
class MainActivity : MyActivity<ViewDataBinding, MainViewModel>() {

    val icons = arrayOf(R.drawable.ic_home_c, R.drawable.ic_trad_c, R.drawable.ic_wallet_c)
    val fragments = arrayOf(HomeFragment(), TradingFragment(), WalletFragment())

    val mainVm by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java) }
//    var webSocketService: WebSocketService? = null

    var canExit = false

    override fun initVariableId() = BR.mainVm

    override fun initContentView(savedInstanceState: Bundle?) = R.layout.activity_main

    override fun initViewModel() = mainVm

//    private val connection = object : ServiceConnection {
//        override fun onServiceDisconnected(name: ComponentName?) {}
//        override fun onServiceConnected(name: ComponentName?, service: IBinder) {
//            webSocketService = (service as WebSocketService.WebSocketBinder).getService()
//            webSocketService?.onReceiveListener = { GlobalScope.launch(Dispatchers.Main) { onReceiveMsg(it) } }
//            webSocketService?.startWsClient()
//        }
//    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setColor(this,resources.getColor(R.color.colorPrimary),80)
        if (MyApplication.sp.getBoolean(Constant.SP.SP_KEY_FIRST_GO_HOME,true)){
            go(RouterIndex.GUIDE, mapOf(
                Constant.ROUTE_PARAMS_KEY.GUIDE_IMAGE to arrayListOf(
                    R.drawable.home_1,
                    R.drawable.home_2,
                    R.drawable.home_3)))
        }
        MyApplication.sp.edit().putBoolean(Constant.SP.SP_KEY_FIRST_GO_HOME,false).apply()
        tvTitle.text = mainVm.titles[0]
        mainVm.titleText.addOnPropertyChangedCallback(BaseOnPropertyChangedCallback<ObservableField<String>>{sender,_->
            tvTitle.text = sender.get()
        })
        ivBack.visibility = View.GONE

        val item1 = AHBottomNavigationItem("首页", icons[0])
        val item2 = AHBottomNavigationItem(mainVm.titles[1], icons[1])
        val item3 = AHBottomNavigationItem(mainVm.titles[2], icons[2])

        MyApplication.userInfo.addOnPropertyChangedCallback(BaseOnPropertyChangedCallback<ObservableField<UserDescBean>>{ sender, _->
            if (viewModel.currentIndex.get() == 0){
                viewModel.titles[0] = /*MyApplication.userInfo.get()?.truename?.makeSalt()?:*/viewModel.titles[0]
                viewModel.titleText.set(viewModel.titles[0])
            }
        })

        bottomNavigation.addItem(item1)
        bottomNavigation.addItem(item2)
        bottomNavigation.addItem(item3)
        bottomNavigation.isBehaviorTranslationEnabled = false
        bottomNavigation.accentColor = resources.getColor(R.color.colorPrimary)
        bottomNavigation.isForceTint = true
        bottomNavigation.titleState = AHBottomNavigation.TitleState.ALWAYS_SHOW

        bottomNavigation.setOnTabSelectedListener { position, _ ->
            mainVm.currentIndex.set(position)
            return@setOnTabSelectedListener true
        }

        vpContent.adapter = BaseFragmentPagerAdapter(supportFragmentManager, fragments)

//        val intent = Intent(this, WebSocketService::class.java)
//        startService(intent)
//        bindService(intent, connection, Context.BIND_AUTO_CREATE)
        viewModel.addAlert.observe(this, Observer {
            if (it != null) {
                (fragments[0] as HomeFragment).addAlerts(it)
                viewModel.getUserInfo()
            }
        })
        update()
        ignoreBatteryOptimization(this)
    }

    override fun onBackPressed() {
        if (canExit) {
            super.onBackPressed()
        } else{
            toast("再按一次返回键退出")
            canExit = true
            GlobalScope.launch(Dispatchers.Main) {
                delay(2000)
                canExit = false
            }
        }
    }


    override fun onResume() {
        super.onResume()
        viewModel.getUserInfo()
    }

//    override fun onDestroy() {
//        super.onDestroy()
//        unbindService(connection)
//    }

    @SuppressLint("BatteryLife")
    private fun ignoreBatteryOptimization(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
            val hasIgnored = powerManager.isIgnoringBatteryOptimizations(activity.packageName)
            //  判断当前APP是否有加入电池优化的白名单，如果没有，弹出加入电池优化的白名单的设置对话框。
            if (!hasIgnored) {
                val intent = Intent(ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
                intent.data = Uri.parse("package:${activity.packageName}")
                startActivity(intent)
            }
        }
    }

//    fun onReceiveMsg(text: String) {
//        try {
//            val msg = Constant.gson.fromJson(text, HttpResult::class.java)
//            if (msg.type == "dispatch") {
//                val mapType = ParameterizedTypeImpl(ArrayList::class.java, arrayOf(OrderDescBean::class.java))
//                val type = ParameterizedTypeImpl(HttpResult::class.java, arrayOf(mapType))
//                val result: HttpResult<ArrayList<OrderDescBean>?> = Constant.gson.fromJson(text, type)
//                if (result.data != null && result.data.isNotEmpty()) {
//                    viewModel.addAlert.value = result.data
//                    webSocketService?.send("{\"type\":\"is_cancel\",\"order_no\":\"${result.data[0].order_no}\"}")
//                    val pIntent = Intent(MyApplication.applicationContext, OrderDescActivity::class.java)
//                    pIntent.putExtra(Constant.ROUTE_PARAMS_KEY.ORDER_ID, result.data[0].id)
//                    NotificationUtils.sendNotification(
//                        "收到一笔新订单",
//                        "点击查看详情",
//                        PendingIntent.getActivity(
//                            MyApplication.applicationContext,
//                            0,
//                            pIntent,
//                            PendingIntent.FLAG_UPDATE_CURRENT
//                        )
//                    )
//                }
//            } else {
//                log("未知消息类型: $text")
//            }
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
//    }

    fun update(){
        GlobalScope.launch(Dispatchers.Main) {
            val async = GlobalScope.async(Dispatchers.IO) {
                tryRun {
                    HttpClient.httpApi.update(BuildConfig.VERSION_NAME).execute()
                }
            }
            val body = async.await()?.body()
            showLoadSuccess()
            if (body?.code == 0) {
                if (body.data.is_update) {
                    val uiData = UIData
                        .create()
                        .setDownloadUrl(body.data.apk_url)
                        .setTitle("有新的应用程序版本")
                        .setContent(body.data.new_version)
                    val instance = AllenVersionChecker.getInstance().downloadOnly(uiData)
                    if (body.data.is_force_update) {
                        instance.setForceUpdateListener {
                            MyActivityManager.exitApp()
                        }
                    }
                    instance.setForceRedownload(true)
                        .setNotificationBuilder(
                            NotificationBuilder.create()
                                .setRingtone(true)
                                .setIcon(R.mipmap.ic_launcher)
                                .setTicker(resources.getString(R.string.appName))
                                .setContentTitle("检查更新")
                                .setContentText("有新版本可用")
                        )
                        .setDownloadAPKPath(Constant.FilePath.DATA_CACHE_FOLDER)
                        .executeMission(this@MainActivity)
                }
            }
        }
    }
}
